﻿using System;
using System.Collections.Generic;
using System.Text;
using TTClassLibrary;
using TTServer.Messages;
using libCommonClass;
using TTServer.Controller;
using libInterface;
using libUtilities;
using System.Drawing;
using bmttPPTController.TTServer;

namespace TTServer.MessageProcessor
{
    public class PPTGoToSlideRequestMessageProcessor : IMessageProcessor
    {
        public bool Process(libCommonClass.TTMessage message, libInterface.IClientInfoProvider clientInfoProvider)
        {
            if (message is PPTGoToSlideRequestMessage)
            {
                PPTGoToSlideRequestMessage msg = (PPTGoToSlideRequestMessage)message;

                if (!(clientInfoProvider.Authority == AuthorityConstant.ADMIN
                    || clientInfoProvider.Authority == AuthorityConstant.KEY_MEMBER))
                {
                    return true;
                }

                PPTController pptCtrl = PPTController.Instance;

                if (!pptCtrl.checkPPTApplicationRun())
                {
                    NotifyMessage nm = new NotifyMessage("PPT Controller not run");

                    clientInfoProvider.AddToMessageQueue(nm);

                    return true;
                }

                int idx = ((PPTGoToSlideRequestMessage)msg).SlideIndex;
                if (idx >= 0)
                {
                    pptCtrl.GoToSlide(idx + 1);
                    SendSlideChangedMessage(clientInfoProvider);
                }

                int index = pptCtrl.GetCurrentSlideIndexShowing();
                if (index >= 0)
                {
                    DrawingScreenManager.GetInstance().setCurrentIndex(index - 1);
                }

                return true;
            }

            return false;
        }

        private void SendSlideChangedMessage(IClientInfoProvider clientInfoProvider)
        {
            try
            {
                var img = PPTController.Instance.GetSlideImage();
                if (img == null) return;
                var smallImg = ImageUtils.resizeImage(img, new Size(480, 320));
                var msg = new SlideChangedMessage(clientInfoProvider.TemporaryKey, smallImg);

                clientInfoProvider.AddToMessageQueue(msg);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                throw ex;
            }
        }
    }
}
